﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Threading;
using System.Threading.Tasks;

namespace AvalonAdmin.Utils.UtilEmulatorMonitor
{

    #region 使用方式
  
    //var monitor = new EmulatorMonitor();

    //try
    //{
    //    Console.WriteLine("开始监控模拟器进程...");
    //    await monitor.StartMonitoringAsync();

    //    // 每5秒显示一次监控信息
    //    while (true)
    //    {
    //        Console.Clear();
    //        Console.WriteLine("模拟器监控信息：");
    //        Console.WriteLine("----------------------------------------");

    //        foreach (var info in monitor.Emulators.Values)
    //        {
    //            Console.WriteLine($"进程名: {info.ProcessName}");
    //            Console.WriteLine($"PID: {info.ProcessId}");
    //            Console.WriteLine($"发送量: {info.FormattedBytesSent}");
    //            Console.WriteLine($"接收量: {info.FormattedBytesReceived}");
    //            Console.WriteLine($"运行时长: {info.Uptime:hh\\:mm\\:ss}");
    //            Console.WriteLine($"连接状态: {(info.IsConnected ? "已连接" : "未连接")}");
    //            Console.WriteLine("----------------------------------------");
    //        }

    //        await Task.Delay(5000);
    //    }
    //}
    //catch (Exception ex)
    //{
    //    Console.WriteLine($"监控过程中发生错误: {ex.Message}");
    //}
    //finally
    //{
    //    monitor.StopMonitoring();
    //}
    #endregion

    /// <summary>
    /// 要监控的模拟器信息
    /// 需要安装System.Diagnostics.PerformanceCounter包
    /// </summary>
    public class EmulatorMonitorUtil
    {
        // 要监控的模拟器进程名称列表（不含.exe后缀）
        private readonly List<string> _emulatorProcessNames = new List<string> {
            "HD-Player",      // 夜神模拟器
            "NoxPlayer",      // 蓝叠模拟器
            "MEmu",           // 逍遥模拟器
            "dnplayer",       // 雷电模拟器
            "qemu-system-x86_64" // 安卓官方模拟器
        };

        // 网络流量性能计数器
        private PerformanceCounterCategory _networkCategory;
        private Dictionary<int, PerformanceCounter[]> _networkCounters = new Dictionary<int, PerformanceCounter[]>();

        // 进程信息字典
        public Dictionary<int, EmulatorInfo> Emulators { get; } = new Dictionary<int, EmulatorInfo>();

        // 监控间隔（毫秒）
        private readonly int _monitorInterval = 1000;
        private CancellationTokenSource _cancellationTokenSource;

        public EmulatorMonitorUtil()
        {
            _networkCategory = new PerformanceCounterCategory("Network Interface");
        }

        // 开始监控
        public async Task StartMonitoringAsync()
        {
            _cancellationTokenSource = new CancellationTokenSource();

            try
            {
                while (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    UpdateEmulatorList();
                    UpdateNetworkStats();
                    UpdateConnectionStatus();

                    await Task.Delay(_monitorInterval, _cancellationTokenSource.Token);
                }
            }
            catch (OperationCanceledException)
            {
                // 正常取消监控
            }
        }

        // 停止监控
        public void StopMonitoring()
        {
            _cancellationTokenSource?.Cancel();
        }

        // 更新模拟器列表
        private void UpdateEmulatorList()
        {
            // 获取当前运行的模拟器进程
            var currentProcesses = new List<Process>();
            foreach (var processName in _emulatorProcessNames)
            {
                try
                {
                    currentProcesses.AddRange(Process.GetProcessesByName(processName));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"获取进程 {processName} 失败: {ex.Message}");
                }
            }

            // 移除已结束的进程
            var processesToRemove = new List<int>();
            foreach (var pid in Emulators.Keys)
            {
                if (!currentProcesses.Exists(p => p.Id == pid))
                {
                    processesToRemove.Add(pid);
                }
            }

            foreach (var pid in processesToRemove)
            {
                Emulators.Remove(pid);
            }

            // 添加新进程
            foreach (var process in currentProcesses)
            {
                if (!Emulators.ContainsKey(process.Id))
                {
                    Emulators[process.Id] = new EmulatorInfo
                    {
                        ProcessId = process.Id,
                        ProcessName = process.ProcessName,
                        StartTime = process.StartTime,
                        IsConnected = false,
                        BytesSent = 0,
                        BytesReceived = 0
                    };

                    // 初始化网络计数器
                    InitializeNetworkCounters(process.Id);
                }
            }
        }

        // 初始化网络计数器
        private void InitializeNetworkCounters(int processId)
        {
            try
            {
                // 获取进程关联的网络接口（简化版，实际可能需要更复杂的逻辑）
                var networkInterfaces = _networkCategory.GetInstanceNames();
                var counters = new List<PerformanceCounter>();

                foreach (var nic in networkInterfaces)
                {
                    // 为每个网络接口创建发送和接收计数器
                    counters.Add(new PerformanceCounter("Network Interface", "Bytes Sent/sec", nic));
                    counters.Add(new PerformanceCounter("Network Interface", "Bytes Received/sec", nic));
                }

                if (counters.Count > 0)
                {
                    _networkCounters[processId] = counters.ToArray();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化网络计数器失败 (PID: {processId}): {ex.Message}");
            }
        }

        // 更新网络统计信息
        private void UpdateNetworkStats()
        {
            foreach (var pid in _networkCounters.Keys)
            {
                if (Emulators.TryGetValue(pid, out var info))
                {
                    try
                    {
                        long totalSent = 0;
                        long totalReceived = 0;

                        var counters = _networkCounters[pid];
                        for (int i = 0; i < counters.Length; i += 2)
                        {
                            totalSent += (long)counters[i].NextValue();
                            totalReceived += (long)counters[i + 1].NextValue();
                        }

                        // 转换为累计值（乘以监控间隔秒数）
                        info.BytesSent += (long)(totalSent * (_monitorInterval / 1000.0));
                        info.BytesReceived += (long)(totalReceived * (_monitorInterval / 1000.0));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"更新网络统计信息失败 (PID: {pid}): {ex.Message}");
                    }
                }
            }
        }

        // 更新连接状态（使用 WMI 查询网络连接）
        private void UpdateConnectionStatus()
        {
            try
            {
                using var searcher = new ManagementObjectSearcher(
                    "SELECT * FROM Win32_NetworkConnection WHERE Status='Connected'");

                var connections = searcher.Get();

                foreach (var pid in Emulators.Keys)
                {
                    Emulators[pid].IsConnected = false;

                    // 简化版：只要有网络连接就认为是已连接
                    // 实际应用中可能需要更复杂的逻辑匹配特定进程的连接
                    if (connections.Count > 0)
                    {
                        Emulators[pid].IsConnected = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新连接状态失败: {ex.Message}");
            }
        }
    }

    /// <summary>
    /// 模拟器信息类
    /// </summary>
    public class EmulatorInfo
    {
        public int ProcessId { get; set; }
        public string ProcessName { get; set; }
        public DateTime StartTime { get; set; }
        public long BytesSent { get; set; }
        public long BytesReceived { get; set; }
        public bool IsConnected { get; set; }

        // 计算运行时长
        public TimeSpan Uptime => DateTime.Now - StartTime;

        // 格式化网络流量
        public string FormattedBytesSent => FormatBytes(BytesSent);
        public string FormattedBytesReceived => FormatBytes(BytesReceived);

        private string FormatBytes(long bytes)
        {
            string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
            int order = 0;
            double size = bytes;

            while (size >= 1024 && order < suffixes.Length - 1)
            {
                order++;
                size /= 1024;
            }

            return $"{size:0.##} {suffixes[order]}";
        }
    }
}
